<template>
  <div class="login">
    <van-nav-bar title="登陆页面" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginname"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入合法的用户名!'
          }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,12}$/,
            message: '密码长度6~12位'
          }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Login } from '@/api/user'
import { Toast } from 'vant'
import { mapMutations } from 'vuex'

export default {
  data () {
    return {
      loginname: '17704051019',
      password: '123456'
    }
  },
  methods: {
    ...mapMutations('User', ['setToken']),

    async onSubmit () {
      console.log('111')
      try {
        const res = await Login({
          loginname: this.loginname,
          password: this.password
        })
        if (res.code === 200) {
          console.log(res)
          Toast({
            duration: 800,
            type: 'success',
            message: res.message,
            onClose: () => {
              // 跳转到layout
              // this.$router.push('/')
              console.log(this.$route.query)
              if (this.$route.query.redirect) {
                this.$router.replace(this.$route.query.redirect)
              } else {
                this.$router.replace('/')
              }
            }
          })
          this.setToken(res.data.token)
        } else {
          Toast.fail({
            message: res.message
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    onClickLeft () {
      this.$router.back()
    }
  }
}
</script>

<style lang="scss" scoped>
// ::v-deep(.van-nav-bar .van-icon) {
//   color: #000;
// }
.van-button {
  background-color: #c82519;
  border: 0;
}
</style>
